package com.ship.dispatch.service.fob.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.dispatch.bean.SpDispatchSchemeExecute;
import com.ship.dispatch.bean.SpPortInformation;
import com.ship.dispatch.bean.fob.*;
import com.ship.dispatch.bpm.utils.JsonUtils;
import com.ship.dispatch.bpm.utils.TemplateParamUtils;
import com.ship.dispatch.bpm.vo.ManageEntityVo;
import com.ship.dispatch.mapper.SpPortInformationMapper;
import com.ship.dispatch.mapper.fob.SpFobReturnSalesZddsfjlMapper;
import com.ship.dispatch.mapper.fob.SpFobZddsfjlMapper;
import com.ship.dispatch.service.SpDispatchSchemeExecuteService;
import com.ship.dispatch.service.fob.SpFobFileRecordService;
import com.ship.dispatch.service.fob.SpFobReturnSalesMfqrzzxxService;
import com.ship.dispatch.service.fob.SpFobReturnSalesZddsfjlService;
import com.ship.dispatch.service.fob.SpFobTemplateService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yl
 * @title SpFobReturnSalesZddsfjlServiceImpl
 * @description 003返装销售-指定装载港第三方计量
 * @create 2024/1/3 0003
 */
@Service
public class SpFobReturnSalesZddsfjlServiceImpl extends FobBaseServiceImpl<SpFobReturnSalesZddsfjlMapper,SpFobReturnSalesZddsfjl> implements SpFobReturnSalesZddsfjlService {

    @Autowired(required = false)
    SpFobReturnSalesZddsfjlMapper mapperapper;
    @Autowired(required = false)
    SpFobZddsfjlMapper spFobZddsfjlMapper;

    @Autowired
    SpFobFileRecordService spFobFileRecordService;
    @Autowired
    SpDispatchSchemeExecuteService schemeDetailService;

    @Autowired
    SpFobTemplateService spFobTemplateService;

    @Autowired
    SpFobReturnSalesMfqrzzxxService spFobReturnSalesMfqrzzxxService;

    @Override
    public void updateEntity(ManageEntityVo manageEntityVo, String json) {
        SpFobReturnSalesZddsfjl object = JsonUtils.jsonToObject(json,SpFobReturnSalesZddsfjl.class);
        SpFobReturnSalesZddsfjl his = mapperapper.selectOne(new LambdaQueryWrapper<SpFobReturnSalesZddsfjl>().eq(SpFobReturnSalesZddsfjl::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobReturnSalesZddsfjl::getStatus,-2));
        if(manageEntityVo.getOperationType()==1) {
            object.setStatus(1);
        }
        if(his==null){ // 新增
            object.setSchemeDetailId(manageEntityVo.getSchemeDetailId());
            object.setTaskId(manageEntityVo.getTaskId());
            object.setProceeInstanceId(manageEntityVo.getProcessInstanceId());
            mapperapper.insert(object);
        }else { // 修改
            object.setId(his.getId());
            BeanUtils.copyProperties(object,his);
            mapperapper.updateById(his);
            // 处理多余文件记录
            List<String> ids = new ArrayList<>();
            if((his.getFiels()!=null && his.getFiels().length()>0)){
                String temp = his.getFiels();
                String[] fieldIds = temp.split(",");
                ids =  Arrays.stream(fieldIds).collect(Collectors.toList());
            }
            spFobFileRecordService.deleteOtherFileRecor(his.getId(),ids);
        }
    }

    @Override
    public SpFobBaseBean getBaseBeanByInstanceId(String id) {
        return mapperapper.selectOne(new LambdaQueryWrapper<SpFobReturnSalesZddsfjl>().eq(SpFobReturnSalesZddsfjl::getProceeInstanceId,id).ne(SpFobReturnSalesZddsfjl::getStatus,-2));
    }
    @Override
    public void  saveEntity(SpFobBaseBean bean){
        SpFobReturnSalesZddsfjl spFobZzgcjr = new SpFobReturnSalesZddsfjl();
        BeanUtils.copyProperties(bean,spFobZzgcjr);
        this.save(spFobZzgcjr);
    }

    @Override
    public void updateEntityById(SpFobBaseBean bean) {
        SpFobReturnSalesZddsfjl spFobZzgcjr = new SpFobReturnSalesZddsfjl();
        BeanUtils.copyProperties(bean,spFobZzgcjr);
        this.updateById(spFobZzgcjr);
    }


    @Override
    public Object getFormData(String id,Long serviceId) {
        SpFobReturnSalesZddsfjl spFobZzgcjr = null;
        if(serviceId!=null){
            spFobZzgcjr = mapperapper.selectById(serviceId);
        }else {
            spFobZzgcjr = mapperapper.selectOne(new LambdaQueryWrapper<SpFobReturnSalesZddsfjl>().eq(SpFobReturnSalesZddsfjl::getProceeInstanceId,id).ne(SpFobReturnSalesZddsfjl::getStatus,-2));
        }
        if(spFobZzgcjr==null){
            return null;
        }
        Map<String,Object> map = JsonUtils.jsonToMap(JsonUtils.objectToJson(spFobZzgcjr), Object.class);
        if(StringUtils.isNotBlank(spFobZzgcjr.getFiels())){
            String[] ids = spFobZzgcjr.getFiels().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("fiels",spFobFileRecordList);
        }
        SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(spFobZzgcjr.getProceeInstanceId());
        if (execute.getExpectedLoadingPort()!=null && spFobZzgcjr.getPort() == null){
            map.put("port",execute.getExpectedLoadingPort());
        }
        return map;
    }
    @Autowired(required=false)
    SpPortInformationMapper spPortInformationMapper;

    @Override
    public String  getTemplateParam(ManageEntityVo manageEntityVo) {
        ObjectNode json = manageEntityVo.getData();
        SpFobReturnSalesZddsfjl spFobZzgcjr = JsonUtils.jsonToObject(JsonUtils.objectToJson(json),SpFobReturnSalesZddsfjl.class);
        String  templateId = spFobZzgcjr.getTemplateId();
        if(templateId==null){
            throw  new BusException("请选模板后再生成模板正文", BaseResultCode.GENERAL_ERROR);
        }
        SpFobTemplate spFobTemplate = spFobTemplateService.getById(templateId);
        if(spFobTemplate == null){
            throw  new BusException("当前模板不存在，请联系管理员处理", BaseResultCode.GENERAL_ERROR);
        }
        // 调度方案信息
        SpDispatchSchemeExecute schemeDetail = schemeDetailService.getExceuteByInstanceId(manageEntityVo.getProcessInstanceId());
        Map<String,String> map = new HashMap<>();
        if(schemeDetail!=null){
            Map<String,String> tempMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(schemeDetail),String.class);
            for(String key:tempMap.keySet()){
                map.put("spDispatchSchemeDetail."+key,tempMap.get(key));
            }
        }
        if(spFobZzgcjr.getCronId()!=null){ // 获取第三方计量合同
            Map<String,String> tempMap = spFobZddsfjlMapper.findConThirdPartyMeasurement(spFobZzgcjr.getCronId());
            for(String key:tempMap.keySet()){
                String tempKey = JsonUtils.toCamelCase(key);
                map.put("conThirdPartyMeasurement."+tempKey,tempMap.get(key));
            }
            if("1".equals(tempMap.get("trade_body"))){
                map.put("temp2","Hong kong");
                map.put("temp1","CNOOC Gas and Power Trading& Marketing Limited");
                map.put("temp3","GPTM");
            }else {
                map.put("temp2","Singapore");
                map.put("temp1","CNOOC Gas and Power Singapore Trading& Marketing Pte. Ltd");
                map.put("temp3","SG");
            }
        }
        SpPortInformation spPortInformation  = null;
        if(schemeDetail.getExpectedLoadingPort()!=null){ // 获取港口信息
            spPortInformation = spPortInformationMapper.selectOne(new LambdaQueryWrapper<SpPortInformation>()
                    .eq(SpPortInformation::getPortNameEnglish,schemeDetail.getExpectedLoadingPort())
                    .or().eq(SpPortInformation::getPortNameChinese,schemeDetail.getExpectedLoadingPort())
                    .last("LIMIT 1")
            );
        }
        if(spPortInformation!=null){
            //map.put("spDispatchSchemeDetail.expectedUnloadingPort",spPortInformation.getPortNameEnglish());
            map.put("spPortInformation.portCountry",spPortInformation.getPortCountry());
        }else{
            map.put("spPortInformation.portCountry","");
        }        // 当前业务表单信息
        if(json!=null){
            Map<String,String> tempMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(json),String.class);
            for(String key:tempMap.keySet()){
                map.put("spFobReturnSalesZddsfjl."+key,tempMap.get(key));
            }
        }
        String  template = TemplateParamUtils.processDynamicParams(spFobTemplate.getContent(),map);
        return template;
    }


    @Override
    public List<Long> findServieData(String processInstanceId){
        List<SpFobReturnSalesZddsfjl> spFobBaseBeans =  mapperapper.selectList(new LambdaQueryWrapper<SpFobReturnSalesZddsfjl>().eq(SpFobReturnSalesZddsfjl::getProceeInstanceId,processInstanceId).orderByDesc(SpFobReturnSalesZddsfjl::getCreateDate));
        List<Long> list = spFobBaseBeans.stream().map(SpFobBaseBean::getId).collect(Collectors.toList());
        return list;
    }

    @Override
    public String findThirdJlData(String processInstanceId) {
        SpFobReturnSalesZddsfjl spFobZzgcjr = mapperapper.selectOne(new LambdaQueryWrapper<SpFobReturnSalesZddsfjl>().eq(SpFobReturnSalesZddsfjl::getProceeInstanceId,processInstanceId).ne(SpFobReturnSalesZddsfjl::getStatus,-2));
        if(spFobZzgcjr.getCronId()!=null) { // 获取第三方计量合同
            Map<String, String> tempMap = spFobZddsfjlMapper.findConThirdPartyMeasurement(spFobZzgcjr.getCronId());
            if(tempMap.containsKey("party_b") && tempMap.get("party_b")!=null){
                return tempMap.get("party_b");
            }
        }
        return null;
    }
}
